package com.xry.test1.service;

import com.xry.test1.Util.JWTUtil;
import com.xry.test1.model.User;
import com.xry.test1.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户注册
     */
    public void register(String username, String password) {

        Optional<User> userOpt = userRepository.findByUsername(username);
        if (!userOpt.isEmpty()) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 这里可以加密保存：BCrypt 等
        userRepository.save(user);
    }

    /**
     * 用户登录，返回 token
     */
    public String login(String username, String password) {
        System.out.println("尝试登录的用户名: " + username);  // 打印尝试登录的用户名
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) {
            System.out.println("用户不存在");
            throw new RuntimeException("用户不存在 异常抛出");  // 抛出异常
        }

        User user = userOpt.get();

        // 打印用户名和密码
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        if (!user.getPassword().equals(password)) { // 明文对比，建议后续使用加密方式
            throw new RuntimeException("密码错误");
        }

        return JWTUtil.createToken(user.getUsername());
    }

}
